import SQLite from 'react-native-sqlite-storage';
import {DB_FD, DB_ST} from '../utils/DBFields';
import RNFS from 'react-native-fs';

import {SNPluginManager} from 'rtn-supernote-plugin-core';
import NativeStickerUtils from 'react-native-sticker-lib/src/NativeStickerUtils';

const defaultDBVersion = 0;

const DB_DEFAULT_NAME = "system_stickers_db";

// 初始化数据库
const db = SQLite.openDatabase(
  {name: DB_FD.DB_NAME, location: DB_FD.STICKER_LOCATION},
  () => {
    console.log('Database OPENED');
  },
  error => {
    console.error('Database OPEN ERROR: ', error);
  },
);

let defaultDB = null;

const initDefaultDB = async () => {
 try {
  await NativeStickerUtils.updateSystemDB(defaultDBVersion);

  defaultDB =  SQLite.openDatabase(
    {name: DB_FD.DB_DEFAULT_NAME, location: DB_FD.STICKER_LOCATION},
    () => {
      console.log('Database default OPENED');
    },
    error => {
      console.error('Database default OPEN ERROR: ', error);
    },
  );



 } catch (e) {
   console.log(e, '初始化数据库');
 } 
}


// 创建表（在应用启动时执行一次）
const createTables = async () => {
  await db_fun(DB_ST.STICKER_GROUP_TABLE_ST, []);
  await db_fun(DB_ST.STICKER_TABLE_ST, []);
  // await db_default_fun(DB_ST.STICKER_GROUP_TABLE_ST, []);
  // await db_default_fun(DB_ST.STICKER_TABLE_ST, []);
};

// 查询所有数据
const db_fun = (db_st, arg = []) => {
  return new Promise((resolve, reject) => {
    try {
      db.transaction(tx => {
        tx.executeSql(
          db_st,
          arg,
          (tx, results) => {
            console.log('queryAllFromDatabase results', db_st, results);
            console.log(' results.rows.raw()', results.rows.raw());
            const rows = results.rows.raw();
            resolve({code: 200, data: rows, results});
          },
          (tx, error) => {
            // 如果 SQL 执行出错，我们使用 reject 来传递错误
            console.error('SQL ERROR', db_st, error);
            reject({code: 500, ...error});
          },
          error => {
            // 如果事务出错，我们也使用 reject 来传递错误
            console.error('Transaction ERROR', db_st, error);
            reject(error);
          },
        );
      });
    } catch (e) {
      console.log(e, '查询所有数据');
      reject(e);
    }
  });
};
const db_default_fun = (db_st, arg = []) => {
  return new Promise((resolve, reject) => {
    try {
      defaultDB?.transaction(tx => {
        tx.executeSql(
          db_st,
          arg,
          (tx, results) => {
            console.log('default queryAllFromDatabase results', db_st, results);
            console.log('default  results.rows.raw()', results.rows.raw());
            const rows = results.rows.raw();
            resolve({code: 200, data: rows, results});
          },
          (tx, error) => {
            // 如果 SQL 执行出错，我们使用 reject 来传递错误
            console.error('default SQL ERROR', db_st, error);
            reject({code: 500, ...error});
          },
          error => {
            // 如果事务出错，我们也使用 reject 来传递错误
            console.error('default Transaction ERROR', db_st, error);
            reject(error);
          },
        );
      });
    } catch (e) {
      console.log(e, '查询所有数据');
      reject(e);
    }
  });
};

// 根据 ID 删除数据
const db_del = async (db_st, ids) => {
  const placeholders = Array(ids.length).fill('?').join(',');
  return await db_fun(db_st + '(' + placeholders + ')', ids);
};

// 初始化数据库和导出函数
(async () => {
  await initDefaultDB();
  await createTables();
})();

const Index = {
  db_fun,
  db_del,
  db_default_fun,
};

module.exports = Index;
